// pages/linkpicpage/linkpicpage.js
var ctx = null;
var canvasw = 0; //画布宽度
var canvash = 0; //画布高度
const fsize = [];
for (let i = 20; i <= 60; i = i + 4) {
  fsize.push(i)
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    imgcount: 0,
    canvasw: 0,
    canvash: 0,
    totalheight: 0,
    textval: '',
    x: 0,
    y: 0,
    fontsize: 20,
    fontsizes: fsize,
    sizeindex: 0,
    fontcolorhex: ['#000000', '#FFB6C1', '#FF69B4', '#C71585', '#ff0000', '#FF8C00', '#FFD700', '#ADFF2F', '#00FF00', '#008000', '#2E8B57', '#00CED1', '#0000FF', '#00008B', '#4B0082', '#9400D3', '#ffffff'],
    fontcolor: '#000000',
    colorindex: 0,
    istext: false,
    istexttool:false,
  },

  //画布初始化执行
  startCanvas: function () {
    var that = this
    //创建canvas
    ctx = wx.createCanvasContext('linkimgs');
    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        // console.log(res)
        // let h = 100
        let h = 100
        if (res.windowHeight - res.windowWidth > 300) {
          h = 200
        }
        if (res.windowHeight - res.windowWidth < 200) {
          h = 50
        }
        let canvasw = res.windowWidth - 0; //设备宽度
        let canvash = canvasw + h;
        that.setData({
          canvasw: canvasw
        });
        // that.setData({
        //   canvash: canvash
        // });

      },
      fail: function (res) {
        wx.showToast({
          title: '初始化失败，请重试！',
        })
      },
    });

  },
  // 选图
  chooseimg: function () {
    let that = this

    wx.chooseImage({
      count: 1,
      success: function (res) {
        // console.log(res)
        // that.data.imgs.push(res.tempFilePaths[0])
        // that.setData({
        //   totalheight: 0,
        //   imgcount: 0,
          
        // })
        // console.log(that.data.imgs)
        // for (let i = 0; i < that.data.imgs.length; i++) {
          
          wx.getImageInfo({
            // src: that.data.imgs[i],
            src: res.tempFilePaths[0],
            success: function (res) {
              // console.log(res)

              let width = res.width
              let height = res.height
              if (width > that.data.canvasw) {
                width = that.data.canvasw
                height = height / res.width * width
              }
              ctx.drawImage(res.path, (that.data.canvasw - width) / 2, that.data.totalheight, width, height)
              that.data.totalheight = that.data.totalheight + height
              that.setData({
                canvash: that.data.totalheight
              })

              // that.data.imgcount = that.data.imgcount + 1
              // if (that.data.imgcount == that.data.imgs.length) {
                // console.log(that.data.imgcount)
                // console.log(that.data.imgs.length)
                ctx.draw(true)
              // }

            }
          })


        // } //for


      }
    })


  },
  // 文字菜单
  texttool:function(){
    if (this.data.istexttool){
      this.setData({
        istexttool:false,
      })
    }else{
      this.setData({
        istexttool: true,
      })
    }
  },
  // 取文字
  textval: function (e) {
    this.setData({
      textval: e.detail.value
    })
  },
  // 设置文字
  addtext: function () {

    if (this.data.canvash == 0) {
      wx.showToast({
        title: '还没有图片！',
        icon: 'none'
      })
      return
    }
    if (this.data.textval.replace(/(^\s*)|(\s*$)/g, "") == '') {
      wx.showToast({
        title: '还没有文字！',
        icon: 'none'
      })
      return
    }
    
      let initx = 100
      let inity = 100
      if (this.data.x != 0) {
        initx = this.data.x
      }
      if (this.data.y != 0) {
        inity = this.data.y
      }

      let ctxtext = wx.createCanvasContext('canvastext')
      ctxtext.setFillStyle(this.data.fontcolor)
      ctxtext.setFontSize(this.data.fontsize)
      ctxtext.fillText(this.data.textval, initx, inity)
      ctxtext.draw()
      this.setData({
        istext: true,
      })
    
  },
  // 文字样式最终确定
  finaltext: function () {

    if (!this.data.istext) {
      wx.showToast({
        title: '还没有设置文字！',
        icon: 'none'
      })
      return
    }
    wx.showModal({
      title: '提示',
      content: '确定后文字不能修改',
      success: (res) => {
        if (res.confirm) {
          let initx = 100
          let inity = 100
          if (this.data.x != 0) {
            initx = this.data.x
          }
          if (this.data.y != 0) {
            inity = this.data.y
          }
          ctx.setFillStyle(this.data.fontcolor)
          ctx.setFontSize(this.data.fontsize)
          ctx.fillText(this.data.textval, initx, inity)
          ctx.draw(true)
          this.setData({
            x:100,
            y:100,
            istext:false,
            
          })
          let ctxtext = wx.createCanvasContext('canvastext')
          ctxtext.fillText("", 0, 0)
          ctxtext.draw()
          wx.showToast({
            title: 'OK',
          })
        }
      }
    })

  },

  // 移动文字
  canvasmovestart: function (e) {
    if (this.data.istext) {
      let x = e.touches[0].x
      let y = e.touches[0].y
      this.setData({
        x: x,
        y: y,
      })
    }
  },
  canvasmoveon: function (e) {
    if (this.data.istext) {
      let movex = e.touches[0].x
      let movey = e.touches[0].y
      let ctxtext = wx.createCanvasContext('canvastext')
      let txtwidth = ctxtext.measureText(this.data.textval)
      if (movex<0){
        movex=0
      }
   
      if (movey < 16) {
        movey = 16
      }
      if (movex > this.data.canvasw -txtwidth.width){
        movex = this.data.canvasw - txtwidth.width
      }
      if (movey > this.data.canvash) {
        movey = this.data.canvash
      }
      ctxtext.setFillStyle(this.data.fontcolor)
      ctxtext.setFontSize(this.data.fontsize)
      ctxtext.fillText(this.data.textval, movex, movey)
      ctxtext.draw()
      this.setData({
        x: movex,
        y: movey,
      })
  }
  },
  // 文字大小
  selectsize: function (e) {
    let sizindex = e.detail.value
    let size = this.data.fontsizes[sizindex]
    this.setData({
      sizeindex: sizindex,
      fontsize: size
    })
    // this.addtext()
  },
  // 文字颜色
  selectcolor: function (e) {
    let colindex = e.detail.value
    let color = this.data.fontcolorhex[colindex]
    this.setData({
      colorindex: colindex,
      fontcolor: color
    })
    // this.addtext()
  },
  // 清除文字
  cleartext: function () {
    if(!this.data.istext){
      wx.showToast({
        title: '没有可以清除的文字！',
        icon:'none',
      })
      return
    }
    let that=this
    wx.showModal({
      title: '提示',
      content: '确定清除文字？',
      success: (res) => {
        if (res.confirm) {
          let ctxtext = wx.createCanvasContext('canvastext')
          ctxtext.fillText("", 0, 0)
          ctxtext.draw()
          that.setData({
            x:100,
            y:100,
            istext:false,
          })
          
        }
      }
    })

  },
  // 清除
  clearimg: function () {
    let that = this
    wx.showModal({
      title: '提示',
      content: '确定清除？',
      success: (res) => {
        if (res.confirm) {
          ctx.clearRect(0, 0, that.data.canvasw, that.data.totalheight)
          ctx.draw()
          that.setData({
            imgs: [],
            totalheight: 0,
            canvash: 0,
            imgcount: 0,
            x: 100,
            y: 100,
            istext: false,

          })
          let ctxtext = wx.createCanvasContext('canvastext')
          ctxtext.fillText("", 0, 0)
          ctxtext.draw()
        }
      }
    })
  },
  // 保存
  saveimg: function () {
    let that = this
    if (that.data.canvash == 0) {
      wx.showToast({
        title: '还没有图片！',
        icon: 'none'
      })
      return
    }
    if (that.data.istext) {
      wx.showToast({
        title: '还没确定文字！',
        icon: 'none'
      })
      return
    }
    wx.showModal({
      title: '提示',
      content: '确定保存图片到相册？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '保存中...',
          })
          //生成临时图
          wx.canvasToTempFilePath({
            canvasId: 'linkimgs',
            success(res) {
              // console.log(res.tempFilePath)
              //存图到相册
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,

                success(res) {
                  // res.authSetting['scope.writePhotosAlbum']
                  // console.log(res)
                  wx.hideLoading()
                  wx.showToast({
                    title: '保存成功！',
                  })
                  that.setData({
                    imgs: [],
                    totalheight: 0,
                    canvash: 0,
                    imgcount: 0,
                    x: 100,
                    y: 100,
                    istext: false,
                  })
                  let ctxtext = wx.createCanvasContext('canvastext')
                  ctxtext.fillText("", 0, 0)
                  ctxtext.draw()
                },
                fail(res) {
                  // console.log(res.authSetting['scope.writePhotosAlbum'])
                  console.log(res)
                  if (res.errMsg == "saveImageToPhotosAlbum:fail cancel") {
                    wx.hideLoading()
                    wx.showToast({
                      title: '取消保存！',
                      icon: 'none',
                    })
                  } else if (res.errMsg == "saveImageToPhotosAlbum:fail getaddrinfo ENOTFOUND servicewechat.com servicewechat.com:443") {
                    wx.hideLoading()
                    wx.showToast({
                      title: '保存失败，请联网！',
                      icon: 'none',
                    })
                  } else {
                    wx.hideLoading()
                    wx.showToast({
                      title: '保存失败，请授权！',
                      icon: 'none',
                    })
                  }
                }
              })
            },
            fail(res) {
              wx.showToast({
                title: '保存失败！',
                icon: 'none',
              })
            }
          }) //临时图

        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.startCanvas()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'menu') {
      // 来自页面内转发按钮
      // console.log(res.target)
    }
    return {
      title: '拼接图片',
      path: '/pages/linkpicpage/linkpicpage'
    }
  }
})